package heap;

import java.util.*;

/*
 *@description 查找和最小的 K 对数字
 *@author hkfan
 *@version 1.0
 *@create 2025/6/23 16:50
 */
public class LeetCode_502 {
    class Item{
        int profit;
        int capital;

        public Item(int profit, int capital) {
            this.profit = profit;
            this.capital = capital;
        }
    }

    public int findMaximizedCapital(int k, int w, int[] profits, int[] capital) {
        //1. 定义变量
        PriorityQueue<Item> minHeap = new PriorityQueue<>((a,b)->{
            return a.capital-b.capital;
        });
        PriorityQueue<Item> maxHeap = new PriorityQueue<>((a,b)->{
            return b.profit-a.profit;
        });
        //2. 所有item加入
        for (int i = 0; i < profits.length; i++) {
            minHeap.add(new Item(profits[i],capital[i]));
        }
        //3. 循环
        for (int m = 0; m < k; m++) {
            while (!minHeap.isEmpty()&&minHeap.peek().capital<=w){
                Item item = minHeap.poll();
                maxHeap.add(item);
            }
            Item item = maxHeap.poll();
            w+=(item!=null)?item.profit:0;
        }
        return w;
    }

}